<?php

/**
 * @author ducnhat
 * @email ddnhat@gmail.com
 * @copyright 2014
 */

class Admin_Model_BuyInvoice extends Zend_Db_Table{
	
	protected $_name    = "order_buys";
    protected $_primary = "id";
    
    public function saveData($data){
    	$db = Zend_Registry::get('db');
        
        $db->beginTransaction();
        
        try{
            $product = $data['product'];
            unset($data['product']);
            
            if(isset($data['order_id']) && $this->checkExists($data['order_id'])){
                $orderID = $id = $data['order_id'];
                unset($data['order_id'])
;
                $db->update("order_buys", $data, "id = $id");
            }else{
                $db->insert('order_buys', $data);
                $orderID = $db->lastInsertId("order_buys");
            }
            
            $this->saveOrderDetail($product, $orderID);
            $this->updateProductBuyQuantity($product);
            
            $db->commit();
            
            return $orderID;
        }catch(Exception $e){
            $db->rollBack();
            
            return false;
        }
    }
    
    public function updateOrders($total, $date, $supplier_id, $old_date = null){
        $db = Zend_Registry::get('db');
        
        if($old_date != null){
            $data1 = array('dept' => new Zend_Db_Expr("dept - $total"),
                        'remaining' => new Zend_Db_Expr("remaining - $total")
                        );
                        
            $where1 = array('date > ?' => "$old_date", 'supplier_id = ?' => $supplier_id);
            
            $db->update('order_buys', $data1, $where1);
        }
        
        $data2 = array('dept' => new Zend_Db_Expr("dept + $total"),
                        'remaining' => new Zend_Db_Expr("remaining + $total")
                        );
        
        $where2 = array('date > ?' => "$date", 'supplier_id = ?' => $supplier_id);
        
        $db->update('order_buys', $data2, $where2);
    }
    
    public function saveOrderDetail($data, $orderID){
    	$db = Zend_Registry::get('db');
        
        $db->delete("order_buy_detail", "order_id = $orderID");
        
        foreach($data as $p){
            $p['order_id'] = $orderID;
            $p['product_id'] = $p['id'];
            unset($p['id']);
            
            $db->insert("order_buy_detail", $p);
        }
    }
    
    public function updateProductBuyQuantity($data){
        $db = Zend_Registry::get('db');
        
        foreach($data as $p){
            $product['id'] = $p['id'];
            $id = $p['id'];
            $product['quantity'] = $p['quantity'] + $this->getProductBuyQuantity($id);
            
            $db->update("product_buys", $product, "id = $id");
        }
    }
    
    private function getProductBuyQuantity($id){
        $db = Zend_Registry::get('db');
        $db->setFetchMode(Zend_Db::FETCH_ASSOC);
        
        $select = $db->select()
                    ->from(array('p' => 'product_buys'), array('id', 'quantity'))
                    ->where("p.id = ?", $id, 'INTEGER');
                    
        $rs = $db->fetchRow($select);
        
        return $rs['quantity'];
    }
    
    public function getDatas($options = null, $cols = array(),$join = true){
    	$db = Zend_Registry::get('db');
        $db->setFetchMode(Zend_Db::FETCH_OBJ);
        
        if(count($cols) == 0){
            $cols = array('id', 'supplier_id', 'number', 'date', 'subtotal', 'totalpay', 'date', 'dept', 'remaining');
        }
        
        $select = $db->select()
                    ->from(array('o' => 'order_buys'), $cols);  
        
        if($join){
            $select->join(array('s' => 'suppliers'), "s.id = o.supplier_id", array('name'));
        }
        
        if($options != null){
            foreach($options as $key => $value){
                $select->{$key}($value);
            }
        }
        
        if(($options != null && !array_key_exists('order', $options)) || $options == null){
            $select->order('o.date DESC')
                    ->order('o.id DESC');
        }
        
        $result = $db->fetchAll($select);
        
        return $result;
    }
    
    public function getData($id){
    	if($this->checkExists($id)){
            $db = Zend_Registry::get('db');
            $db->setFetchMode(Zend_Db::FETCH_ASSOC);
            
            $select = $db->select()
                        ->from(array('o' => 'order_buys'), array('id', 'supplier_id', 'number', 'date', 'dept', 'subtotal', 'totalpay', 'date', 'remaining'))
                        ->join(array('s' => 'suppliers'), "s.id = o.supplier_id", array('name', 'phone_number', 'address'))
                        ->where('o.id = ?', $id, 'INTEGER');
            
            $rs['order'] = $db->fetchRow($select);
            
            $select = $db->select()
                        ->from(array('od' => 'order_buy_detail'), array('product_id', 'price', 'quantity', 'total'))
                        ->join(array('p' => 'product_buys'), "p.id = od.product_id", array('name', 'net', 'type'))
                        ->joinLeft(array('b' => 'brands'), "p.brand = b.id", array('brand'))
                        ->where("order_id = ?", $id, 'INTEGER');
              
            $rs['products'] = $db->fetchAll($select);
            
            return $rs;
        }
        
        return false;
    }
    
    public function getDept($customer_id){
    	$db = Zend_Registry::get('db');
        $db->setFetchMode(Zend_Db::FETCH_ASSOC);
        
        $select = $db->select()
                    ->from(array('o' => 'orders'), array('SUM(subtotal) as total', 'SUM(totalpay) AS totalpay'))
                    ->where("o.status = ?", 1, 'INTEGER')
                    ->where("o.customer_id = ?", $customer_id, 'INTEGER');
                    
        $rs = $db->fetchRow($select);
        
        $dep = 0;
        
        if(count($rs) > 0){
            $dep = $rs['total'] - $rs['totalpay'];
            
            if($dep < 0){
                $dep = 0;
            }
        }
        
        $select = $db->select()
                    ->from(array('d' => 'dept'), array('SUM(dept) as total'))
                    ->where("d.customer_id = ?", $customer_id, 'INTEGER');
                    
        $rs = $db->fetchRow($select);
        
        if(count($rs) > 0){
            $dep += $rs['total'];
        }
        
        return $dep;
    }
    
    public function deleteData($id){
    	$db = Zend_Registry::get('db');
        
        $db->beginTransaction();
        
        try{
            $order = $this->getData($id);
            
            $total = $order['order']['totalpay'] - $order['order']['subtotal'];
            $supplier_id = $order['order']['supplier_id'];
            $date = $order['order']['date'];
            
            $data_order_buys = array('dept' => new Zend_Db_Expr("dept + $total"),
                            'remaining' => new Zend_Db_Expr("remaining + $total")
                            );
                            
            $db->update('order_buys', $data_order_buys, "`date` > '$date' AND supplier_id = $supplier_id");
            
            $products = $order['products'];
            
            foreach($products as $product){
                $quantity = $product['quantity'];
                $pid = $product['product_id'];
                
                $data_product_buys = array('quantity' => new Zend_Db_Expr("quantity - $quantity"));
                $db->update('product_buys', $data_product_buys, "id = $pid");
            }
            
            $db->delete("order_buy_detail", "order_id = $id");
            $db->delete("order_buys", "id = $id");
            
            $db->commit();
            
            return true;
        }catch(Exception $e){
            $db->rollBack();
            
            return false;
        }
    }
    
    public function checkExists($id){
        $option = array('table' => 'order_buys', 'field' => 'id');
    	$validator = new Zend_Validate_Db_RecordExists($option);
        
        if($validator->isValid($id)){
            return true;
        }
        
        return false;
    }
}